package com.itheima.web.controller.system;


import com.github.pagehelper.PageInfo;
import com.itheima.core.BaseServlet;
import com.itheima.core.ResponseBody;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.User;
import com.itheima.service.system.impl.DeptServiceImpl;
import com.itheima.service.system.impl.ModuleServiceImpl;
import com.itheima.service.system.impl.RoleServiceImpl;
import com.itheima.service.system.impl.UserServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@WebServlet("/system/user/*")
public class UserServlet extends BaseServlet {
    private UserServiceImpl userService = new UserServiceImpl();
    private DeptServiceImpl deptService = new DeptServiceImpl();
    private ModuleServiceImpl moduleService = new ModuleServiceImpl();
    private RoleServiceImpl roleService = new RoleServiceImpl();

    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if (StringUtils.isBlank(pageNum)) {
            pageNum = "1";
        }
        if (StringUtils.isBlank(pageSize)) {
            pageSize = "10";
        }
        PageInfo<User> pageInfo = userService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        request.setAttribute("page", pageInfo);
        return "/WEB-INF/pages/system/user/list.jsp";
    }

    @ResponseBody
    public Object findRolesByUserId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");

        List<Map> list = roleService.findRolesByUserId(userId);

        return list;
    }

    public String toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Dept> deptList = deptService.findAll();
        request.setAttribute("deptList", deptList);
        return "/WEB-INF/pages/system/user/add.jsp";
    }

    public String save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");
        userService.save(user);
        return "/system/user/list";
    }

    public String toEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        User user = userService.findById(id);
        request.setAttribute("user", user);
        List<Dept> deptList = deptService.findAll();
        request.setAttribute("deptList", deptList);
        return "/WEB-INF/pages/system/user/update.jsp";
    }

    public String edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");
        userService.update(user);
        return "/system/user/list";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] ids = request.getParameterValues("id");
        userService.deleteById(ids);
        return "/system/user/list";
    }

    /**
     * 跳转到授权页面
     */
    public String toRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*1.获取表单数据*/
        String userId = request.getParameter("id");

//        2.查询详细信息
        User user = userService.findById(userId);

        request.setAttribute("user",user);
        return "/WEB-INF/pages/system/user/author.jsp";
    }


    public Object login(HttpServletRequest request, HttpServletResponse response)throws Exception{
        /*1.获取表单数据*/
        String email = request.getParameter("email");
        String password = request.getParameter("password");

        /*2.调用service*/
        User user = userService.login(email, password);

        /*3.页面跳转*/
        if(user == null){
            request.setAttribute("error","帐号或密码错误");
            return "/login.jsp";
        }else{
            List<Map> modules = moduleService.findModulesByUserId(user.getId());//根据ID查询用户可以操作的模块

            /*拼接用户可以操作的模块的地址*/
            StringBuilder sb = new StringBuilder();
            for (Map module : modules) {
                String curl = (String)module.get("curl");
                sb.append(curl);
                sb.append(",");
            }
            System.out.println(sb);
            System.out.println(modules);

            request.getSession().setAttribute("curls",sb.toString());//该数据存的是用户可以访问的模块地址
            request.getSession().setAttribute("modules",modules);//该数据用于回显菜单
            request.getSession().setAttribute("user",user);
            return "/WEB-INF/pages/home/main.jsp";
        }
    }

    @ResponseBody
    public Object authorize(HttpServletRequest request, HttpServletResponse response){
        try {
            String userId = request.getParameter("userId");
            String str = request.getParameter("roleIds");

            //判断是否需要切割
            if(StringUtils.isBlank(str)){
                userService.updateAuthor(userId,null);
            }else{
                userService.updateAuthor(userId,str.split(","));
            }
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }

    }
}
